package com.atguigu.tingshu.user.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private KafkaService kafkaService;



	@Override
	public BigDecimal getTrackBreakSecond(Long userId,Long trackId) {

		// 构建查询条件
		Query query = new Query();

		query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(trackId));



		// 根据用户id构建表名
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		// 执行查询
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class,
				collectionName);

		if(userListenProcess != null){
			return userListenProcess.getBreakSecond();
		}
		return new BigDecimal("0.00");
	}

	@Override
	public void updateListenProcess(UserListenProcessVo vo,Long userId) {

		// 先查询 MongoDB 中有没有数据，没有就新增，有就更新

		// 构建查询条件
		Query query = new Query();
		query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(vo.getTrackId()));
		// 设置查询第一条记录(避免小程序暂停后恢复播放将积压更新进度请求并发发起，导致新增多条播放进度)
		query.limit(1);

		// 根据用户id构建表名
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		// 执行查询
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class,
				collectionName);

		if(userListenProcess == null){
			// 新增
			userListenProcess = new UserListenProcess();
			userListenProcess.setUserId(userId);
			userListenProcess.setUpdateTime(new Date());
			userListenProcess.setCreateTime(new Date());
			userListenProcess.setAlbumId(vo.getAlbumId());
			userListenProcess.setIsShow(1);
			userListenProcess.setTrackId(vo.getTrackId());
			userListenProcess.setBreakSecond(vo.getBreakSecond());
		}else {
			// 更新
			userListenProcess.setBreakSecond(vo.getBreakSecond());
			userListenProcess.setUpdateTime(new Date());
		}
		mongoTemplate.save(userListenProcess,collectionName);


		// kafka 发送消息，异步更新ablum专辑统计

		// 防止重复发送，采用Redis提供set k v nx ex 确保在规定时间内（24小时/当日内）播放进度统计更新1次
		String key = RedisConstant.USER_TRACK_REPEAT_STAT_PREFIX + userId +":" + vo.getTrackId();
		long ttl = DateUtil.endOfDay(new Date()).getTime() - System.currentTimeMillis();
		Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, userListenProcess.getTrackId(), ttl, TimeUnit.MILLISECONDS);

		if(flag){
			TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
			trackStatMqVo.setTrackId(vo.getTrackId());
			trackStatMqVo.setCount(1);
			trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
			trackStatMqVo.setAlbumId(vo.getAlbumId());
			trackStatMqVo.setBusinessNo(IdUtil.fastSimpleUUID());  // 生成业务唯一标识，消费者端（专辑服务、搜索服务）用来做幂等性处理，确保一个消息只能只被处理一次
			kafkaService.sendMessage(KafkaConstant.QUEUE_TRACK_STAT_UPDATE,JSON.toJSONString(trackStatMqVo));
		}

	}


	@Override
	public Map<String, Long> getLatelyTrack(Long userId) {
		Map<String, Long> resultMap = new HashMap<>();

		// 构建查询语句并执行
		Query query = new Query();
		query.addCriteria(Criteria.where("userId").is(userId));
		query.with(Sort.by(Sort.Direction.DESC,"updateTime"));
		query.limit(1);

		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);

		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);

		if(userListenProcess != null){
			resultMap.put("trackId",userListenProcess.getTrackId());
			resultMap.put("albumId",userListenProcess.getAlbumId());
		}
		return resultMap;
	}
}

























